package com.imooc.zhangxiaoxi.resource;

import org.junit.Test;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

/**
 * @Project 996
 * @ClassName NewFileCopyTest
 * @Description 基于JDK7之后，实现正确关闭流资源的方法
 * @Author pankai@cnsesan.com
 * @CreateTime 2019/11/27 19:21
 * @Modifier
 * @ModifyTime 2019/11/27 19:21
 * @ModifyNote to describe what you modified
 */
public class NewFileCopyTest {
    @Test
    public void copyFile() {
        // 先定义输入输出路径
        String originalUrl = "lib/NewFileCopyTest.java";
        String targetUrl = "targetTest/new.txt";

        // 初始化输入输出流对象
        try (
                FileInputStream originalFileInputStream = new FileInputStream(originalUrl);
                FileOutputStream targetFileOutputStream = new FileOutputStream(targetUrl);
        ) {
            int content;

            // 迭代，拷贝数据
            while ((content = originalFileInputStream.read()) != -1) {
                targetFileOutputStream.write(content);
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
